<script setup>
import { ref, onMounted } from 'vue'
import { getUserListApi,deleteUserApi,getUserByIdApi,addUserApi,updateUserApi,getBirthdayRangeApi } from '@/api/user'
import { Plus,Minus,Search,Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

// 钩子函数
onMounted(() => {
    getList()
})

// 初始化信息
//弹窗
const loading = ref(true)
const centerDialogVisible = ref(false)
//弹窗类型
const add_upate = ref('')
//弹窗信息
const LoadingDate = ref({
        id:'',
        birthday:'',
        buyHour: '',
        userId:'',
        useHour: '',
        giveHour: '',
        sex:'',
        name:'',
        school:'',
        user:{
            username:'',
            password:'',
            parentalName:''
        }
})
//初始化表格数据
const tableData = ref([
    {
        id:'',
        birthday:'',
        buyHour:'',
        userId:'',
        useHour:'',
        giveHour:'',
        allHour:'',
        residueHour:'',
        sex:'',
        name:'',
        school:'',
        createTime:'',
        username:'',
        password:'',
        parentalName:''
    }
])

//修改数据
const update = async(row) => {
    console.log("根据id查询的儿童信息:",row)
    add_upate.value = false
    await getUserByIdApi(row.id).then(res =>{
        LoadingDate.value = res.data
        centerDialogVisible.value = true
        console.log("根据id查询的儿童信息",LoadingDate.value)
    })
}
const sumbitUpdate = async() => {
    await updateUserApi(LoadingDate.value).then(res =>{
        window.location.reload()
        centerDialogVisible.value = false
        ElMessage.success('修改成功')
    }).catch(err => {
        ElMessage.error('修改失败')
    })
}
// 添加数据
const add = () => {
    centerDialogVisible.value = true
    add_upate.value = true
    LoadingDate.value = {
        birthday:'',
        buyHour: '',
        useHour: 0,
        giveHour: '',
        sex:'',
        name:'',
        school:'',
        user:{
            username:'',
            password:'123456',
            parentalName:''
        }
}
}
const sumbitAdd = async() => {
    console.log("添加的信息",LoadingDate.value)
    await addUserApi(LoadingDate.value)
    .then(res =>{
        window.location.reload()
        centerDialogVisible.value = false
        ElMessage.success('添加成功')
    })
    .catch(err => {
        ElMessage.error('添加失败')
    })
}
// 查询近7天生日儿童
const searchBirthday = async() => {
    await getBirthdayRangeApi(page.value)
    .then(res =>{
        tableData.value = res.records
        total.value = res.total
        console.log("近7天生日儿童",res)
    })
}

//条件查询
const search = async() => {
    console.log(page.value)
    getList()
}
//清空分页查询
const clear = () => {
    page.value = {
        page: 1,
        pageSize: 10,
        name: null,
        parentalName: null,
        sex: null,
    }
    getList()
}

// 分页
const total = ref(0)
const page = ref({
    page: 1,
    pageSize: 10,
    name:null,
    parentalName:null,
    sex: null,
})

const handleSizeChange = () => {
    console.log(page.value)
    getList()
}
const handleCurrentChange = () => {
    console.log(page.value)
    getList()
}
// 获取数据
const getList = async () => {
    await getUserListApi(page.value)
    .then(res =>{
        console.log(res)
        tableData.value = res.records
        total.value = res.total
        loading.value = false
    })
}


// 删除
//获取选中行
const arr = ref([])
// 获取选中行id
const handleSelectionChange = (select) => {
    arr.value = select.map(item => item.id)
    console.log("选择中的id",arr.value)
}
// 单个删除
const deletebyid = (row) => {
    arr.value = [row.id]
    console.log("当前对象id：",arr.value)
    sumitDelete()
}
// 批量删除
const sumitDelete = async() => {
    ElMessageBox.confirm('此操作将永久删除该人员，删除后不可恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async() => {
        await deleteUserApi(arr.value)
        .then(res =>{
            ElMessage.success('删除成功')
            getList()
        })
    })
}
</script>

<template>
    <div class="headers">
        <div class="line"></div>
        <div class="title">用户管理</div>
    </div>
    <div style="margin-bottom: 15px;">
        <el-button type="primary" :icon="Plus" @click="add">添加学员</el-button>
        <el-button type="danger" :icon="Minus" @click="sumitDelete">批量删除</el-button>
    </div>
    <div class="ifs">
        <div>
            <span>儿童名：</span>
            <el-input
                v-model="page.name"
                style="width: 180px"
                placeholder="输入儿童名"
                :suffix-icon="Calendar"
                />
        </div>
        <div class="left-margin10">
            <span>家长名：</span>
            <el-input
                v-model="page.parentalName"
                style="width: 180px"
                placeholder="输入家长名"
                :suffix-icon="Calendar"
                />
        </div>
        <div class="left-margin10">
            <span>性别：</span>
            <el-select v-model="page.sex" placeholder="选择性别" size="default" style="width: 150px">
                    <el-option label="全部" value="''" />
                    <el-option label="男"  value="1" />
                    <el-option label="女" value="0" />
                </el-select>
        </div>
        <el-button class="left-margin10" type="success" :icon="Search" @click="search">查询</el-button>
        <el-button class="left-margin10" type="success" :icon="Search" @click="searchBirthday">近7天生日儿童</el-button>
        <el-button class="left-margin10" type="warning" :icon="Delete" @Click="clear">清空</el-button>
    </div>
    <!--表格内容-->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%" :default-sort="{ prop: 'residueHour', order: 'descending' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column fixed property="parentalName" label="家长名" width="120" />
        <el-table-column fixed property="username" label="电话" width="150" />
        <el-table-column fixed property="name" label="儿童名"/>
        <el-table-column property="buyHour" label="购买时长" width="90" />
        <el-table-column property="giveHour" label="赠送时长" width="90" />
        <el-table-column property="buyHour" label="已用时长" width="90" />
        <el-table-column property="allHour" label="总时长" width="90" />
        <el-table-column property="residueHour" label="剩余时长" width="110" sortable >
            <template #default="scope">
                <span :style="{ color: scope.row.residueHour < 5 ? 'red' : 'inherit' }">
                    {{ scope.row.residueHour }}
                </span>
            </template>
        </el-table-column>
        <el-table-column property="sex" label="性别" />
        <el-table-column property="birthday" label="生日" width="150"/>
        <el-table-column property="school" label="学校" width="200" />
        <el-table-column :sortable property="createTime" label="账号生成日期" width="150" />
        <el-table-column property="password" label="密码" width="200" />
        <el-table-column fixed="right" label="Operations" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="deletebyid(scope.row)">
          删除
        </el-button>
        <el-button link type="primary" size="small" @click="update(scope.row)">修改</el-button>
      </template>
    </el-table-column>
    </el-table>




    <!--分页码TODO-->
    <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="page.page"
      v-model:page-size="page.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>





<!-- 添加弹窗 -->
<el-dialog v-model="centerDialogVisible" title="儿童信息表" width="1000" center>
        <!--第一行-->
        <div class="flex gap-4 items-between">
            <div>
                <span>家长名：</span>
                <el-input v-model="LoadingDate.user.parentalName" style="width: 240px" placeholder="输入家长姓名" />
            </div>
            <div>
                <span>电话：</span>
                <el-input v-model="LoadingDate.user.username" style="width: 240px" placeholder="该号码为用户端账号" />
            </div>
            <div>
                <span>密码：</span>
                <el-input v-model="LoadingDate.user.password" style="width: 240px" placeholder="输入密码" />
            </div>
        </div>
        <!--第二行-->
        <div class="flex gap-4 items-between top10">

            <div>
                <span>生日：</span>
                <el-date-picker v-model="LoadingDate.birthday" type="date" placeholder="生日" :size="size"
                    value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
            </div>
            <div>
                <span>学校：</span>
                <el-input v-model="LoadingDate.school" style="width: 240px" placeholder="输入学校" />

            </div>
        </div>
        
        <!--第三行-->
        <div class="flex gap-4 items-between top10">
            <div>
                <span>儿童姓名：</span>
                <el-input v-model="LoadingDate.name" style="width: 180px" placeholder="输入儿童姓名" />
            </div>
            <div>
                <span>性别：</span>
                <el-select v-model="LoadingDate.sex" placeholder="请选择" style="width: 100px;">
                <el-option label="男" value="1" />
                <el-option label="女" value="0" />
            </el-select>
            </div>
            <div>
                <span>购买时长：</span>
                <el-input-number v-model="LoadingDate.buyHour" :min="0"/>
            </div>
            <div>
                <span>赠送时长：</span>
                <el-input-number v-model="LoadingDate.giveHour" :min="0"/>
            </div>
            <div>
                <span>已用时长：</span>
                <el-input-number v-model="LoadingDate.useHour" :min="0" disabled/>
            </div>
        </div>
        <div class="flex gap-4 items-between top10">
            总时长：{{LoadingDate.buyHour + LoadingDate.giveHour}}
        </div>
        <!--弹窗提交按钮-->
        <template #footer>
            <div class="dialog-footer top4">
                <el-button v-if="add_upate" type="primary" @click="sumbitAdd()">添加儿童</el-button>
                <el-button v-else type="primary" @click="sumbitUpdate()">修改儿童</el-button>
            </div>
        </template>
    </el-dialog>



</template>

<style scoped>
.headers {
    display: flex;
    align-items: center;
    height: 30px;
    width: 120px;
    margin-bottom: 20px;
}

.line {
    margin-right: 5px;
    width: 4px;
    height: 100%;
    background-color: aqua;
}

.title {
    font-size: 25px;
    font-family: "楷体";
    font-weight: bold;
}
.demo-pagination-block{
    margin-top: 20px;
    width: 100%;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.ifs{
    display: flex;
    margin-top: 10px;
    margin-bottom: 10px;
}
.left-margin10{
    margin-left: 40px;
}
.items-between {
    display: flex;
    justify-content: space-around;
}
.top10{
    margin-top: 10px;
}
</style>